package cz.possoft.client.saveload;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import cz.possoft.client.loader.ClassLoaderObjectInputStream;
import cz.possoft.serializable.generic.Game;

/**
 * This manager is based on saving games via ObjectOutputStream and loading via ObjectInputStream.
 * 
 * NOTE: if this implementation is used, then server should have access to all "generic" libraries from required games. So this is the
 * reason of deprecation of this class. 
 *  
 * @author mposolda
 * @deprecated
 */
class ObjectStreamsSaveLoadExecutor implements SaveLoadExecutor {

	public Game loadGame(String fileName) throws SaveLoadException {
        ObjectInputStream in = null;
        try {
            in = new ClassLoaderObjectInputStream(new FileInputStream(fileName));
            Object o = in.readObject();
            return (Game)o;
        } catch (Exception e) {
            throw new SaveLoadException("Error in loading game from file " + fileName + ".", e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException exception) {
                    exception.printStackTrace();
                }
            }
        }
	}

	public void saveGame(Game game, String fileName) throws SaveLoadException {
		ObjectOutputStream out = null;
        try {		
        	out = new ObjectOutputStream(new FileOutputStream(fileName));
        	out.writeObject(game);
        	out.flush();
        } catch (IOException io) {
        	throw new SaveLoadException("Can't save game " + game + " to file " + fileName + ".", io);
        } finally {
        	if (out != null) {
        		try {
        			out.close();
        		} catch (IOException exception) {
        			System.err.println("WARNING: Error in closing output stream after saving the game.");
        			exception.printStackTrace();
        		}
        	}
        }
    }	
	
	/**
	 * For this implementation, source should be game itself and this game is also sent to server.
	 */
	public Serializable getObjectForSendingToServer(Game source) {
		return source;
	}
	
	/**
	 * For this implementation, it' assumed that instance of Game is received from server and so this Game is returned from this method.
	 */
	public Game getGameFromServer(Serializable source) {
		return (Game)source;
	}

}
